package com.example.library.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.library.common.Result;
import com.example.library.entity.Appointment;
import com.example.library.entity.Book;
import com.example.library.entity.Borrow;
import com.example.library.mapper.AppointmentMapper;
import com.example.library.service.IAppointmentService;
import com.example.library.service.IBookService;
import com.example.library.service.IBorrowService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 胡绍杆
 * @since 2022-06-16
 */
@ResponseBody
@RestController
@RequestMapping("/appointment")
public class AppointmentController {

    @Resource
    private IAppointmentService iAppointmentService;
    @Resource
    private IBookService iBookService;
    @Resource
    private IBorrowService iBorrowService;
    @Resource
    private AppointmentMapper appointmentMapper;
    /**
     * yang
     * 预约图书subscribe
     * 根据传入的isbn,account进行预约操作，若成功则插入该用户的预约记录
     */
    @Value("${rule.appointmengNums}")
    private Integer appointmengNums;

    @Transactional
    @GetMapping("/setAppointmentByIsbnY")
    public Result setAppointmentByIsbnY(@RequestParam(value = "isbn") String isbn,
                                        @RequestParam(value = "account") String account) {
        try {
            // 判断最近一个月内是否有三次取消记录
            Date date12 = new Date();
            SimpleDateFormat formatter12 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String val12 = formatter12.format(date12);
            Calendar calendar12 = Calendar.getInstance();
            calendar12.set(Calendar.MONTH, calendar12.get(Calendar.MONTH) - 1);
            String beforeMonthDate12 = formatter12.format(calendar12.getTime());
            int num12 = iAppointmentService.count(new QueryWrapper<Appointment>()
                    .eq("account",account)
                    .eq("appointment_state",0)
                    .between("appointment_time",beforeMonthDate12,val12));
            if(num12 < 3){
                // 小于可预约数量
                int num0 = iAppointmentService.count(new QueryWrapper<Appointment>()
                        .eq("account", account)
                        .in("appointment_state", 1, 2));
                if (num0 <= appointmengNums) {
                    // 此书只能预约一次
                    int num1 = iAppointmentService.count(new QueryWrapper<Appointment>()
                            .eq("account", account)
                            .in("appointment_state", 1, 2)
                            .eq("isbn", isbn));
                    if (num1 == 0) {
                        // 判断有无空闲书
                        int num2 = iBookService.count(new QueryWrapper<Book>()
                                .eq("isbn", isbn).eq("book_state", 1));
                        if (num2 == 0) {
                            // 判断有无逾期未归还图书
                            Date date = new Date();
                            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            String val1 = formatter.format(date);
                            Calendar calendar = Calendar.getInstance();
                            calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 2);
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            String beforeMonthDate = simpleDateFormat.format(calendar.getTime());
                            int num3 = iBorrowService.count(new QueryWrapper<Borrow>()
                                    .eq("accout", account)
                                    .isNull("borrow_return")
                                    .between("return_time", beforeMonthDate, val1));
                            if (num3 == 0) {
                                // 插入预约记录
                                Appointment appointment = new Appointment();
                                appointment.setIsbn(isbn);
                                appointment.setAccount(account);
                                appointment.setAppointmentTime(val1);
                                appointment.setAppointmentState(1);
                                if (iAppointmentService.save(appointment)) {
                                    return Result.success(); // 预约成功
                                } else {
                                    return Result.error("100", "预约失败");// 预约失败
                                }
                            } else {
                                return Result.error("101", "有逾期未归还图书"); // 有逾期未归还图书
                            }
                        } else {
                            return Result.error("102", "可直接借阅"); // 可直接借阅
                        }
                    } else {
                        return Result.error("103", "已经预约过此书"); // 已经预约过此书
                    }
                } else {
                    return Result.error("104", "可预约数量已大于预约上限"); // 可预约数量已大于预约上限
                }
            } else {
                return Result.error("107","您最近频繁取消，请稍后再试");
            }


        } catch (Exception e) {
            return Result.error("100", "预约失败");// 预约失败
        }
    }

    /**
     * yang
     * 查看个人预约记录
     * 根据account返回该用户的预约记录
     * pageNum, pageSize, inputStr, account
     */
    @GetMapping("/getAppointmentInfoY")
    public Result getAppointmentInfoY(@RequestParam(value = "pageNum") Integer pageNum,
                                      @RequestParam(value = "pageSize") Integer pageSize,
                                      @RequestParam(defaultValue = "") String inputStr,
                                      @RequestParam(value = "account") String account) {
        return Result.success(appointmentMapper.getAppointmentByAccount(account, pageNum, pageSize));
    }

    /**
     * yang
     * 预约数量
     */
    @GetMapping("/getAppointmentCountY")
    public Result getAppointmentCountY(@RequestParam(value = "account") String account) {
        return Result.success(iAppointmentService.count(new QueryWrapper<Appointment>().eq("account", account)));
    }

    /**
     * yang
     * 取消预约记录
     * 根据传入的预约记录ID和account取消该用户的预约记录
     */
    @GetMapping("/setAppointmentByIdY")
    public Result setAppointmentByIdY(@RequestParam(value = "account") String account,
                                      @RequestParam(value = "appointmentId") String appointmentId) {

        QueryWrapper<Appointment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", account).eq("appointment_id", appointmentId);
        Appointment appointment = iAppointmentService.getOne(queryWrapper);
        // 排队中判断
        UpdateWrapper<Appointment> updateWrapper1 = new UpdateWrapper<>();
        updateWrapper1.eq("account", account)
                .eq("appointment_id", appointmentId)
                .set("appointment_state", 0);
        iAppointmentService.update(updateWrapper1);
        if (appointment.getAppointmentState() == 2) {
            // 待取书判断
            String isbn = appointment.getIsbn();
            UpdateWrapper<Book> updateWrapper2 = new UpdateWrapper<>();
            updateWrapper2.eq("isbn", isbn).eq("book_state", 4).set("book_state", 1).last("limit 1");
            iBookService.update(updateWrapper2);
        }
        return Result.success();
    }

    /**
     * yang
     * 查看预约排名
     * 传入值：isbn,account
     */
    @GetMapping("/getRankY")
    public Result getRankY(@RequestParam(value = "account") String account,
                           @RequestParam(value = "appointmentId") String appointmentId) {
        System.out.println(account + "," + appointmentId);
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String val1 = formatter.format(date);
        // 获取该书isbn
        // 获取我的预约时间
        Appointment appointment = iAppointmentService.getOne(new QueryWrapper<Appointment>()
                .eq("appointment_id", appointmentId));
        String isbn = appointment.getIsbn();
        String pubDa = appointment.getAppointmentTime();
        int num = iAppointmentService.count(new QueryWrapper<Appointment>().eq("isbn", isbn)
                .notBetween("appointment_time", pubDa, val1).eq("appointment_state", 1));
        return Result.success(num+1);
    }


}
